import "reflect-metadata"
import {createConnection} from "typeorm"
import * as Koa from "koa"
import * as Router from "koa-router";
import * as cors from "koa2-cors"
import * as json from "koa-json"
import * as onerror from "koa-onerror"
import * as bodyparser from "koa-bodyparser"
import * as compress from "koa-compress"
import * as logger from "koa-logger"
import * as fileSys from "koa-static"
import { bindRoutes } from "trafficlight"
// import * as session from "koa-generic-session"
import conf from "./config/index"

import apis from "./api/a"


createConnection().then(async connection => {
    // create express app
    const app = new Koa();

    // 设置跨域
    app.use(cors({
        origin: (ctx) => ctx.header.origin,
        exposeHeaders: ["WWW-Authenticate", "Server-Authorization"],
        maxAge: 10,
        credentials: true,
        allowMethods: ["GET", "PUT", "POST", "PATCH", "DELETE", "HEAD", "OPTIONS"],
        allowHeaders: ["Content-Type", "Authorization", "Accept" ,"x-requested-with", "origin", "token"],
    }));

    onerror(app);

    // app.use(session({
    //     store: require('koa-redis')({
    //         host: '127.0.0.1',
    //         port: 6379,
    //         db: 0
    //     })
    // }))

    app.use(bodyparser({
        enableTypes:["json", "form", "text"]
    }));
    app.use(json());
    // gzip
    app.use(compress({
        filter: function (content_type) {
            return /text/i.test(content_type)
        },
        threshold: 2048,
        flush: require("zlib").Z_SYNC_FLUSH
    }))
    app.use(logger());
    app.use(fileSys(__dirname + "/public"));

    // logger
    app.use(async (ctx, next) => {
        const start = new Date().getTime()
        await next();
        const end = new Date().getTime()
        const ms = start - end;
        console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
    });

    //注册路由
    buildRoutes(app)
    // error-handling
    app.on("error", (err, ctx) => {
        console.error("server error", err, ctx);
    });
    // start express server
    app.listen(conf.port)
    console.log(`Express server has started on port ${conf.port}. Open http://localhost:${conf.port} to see results`)
}).catch(error => console.log(error))

function buildRoutes(app) {
    const routerRoutes = new Router();

    // any router can be used, we support koa-router out of the box
    bindRoutes(routerRoutes, apis);

    // if you are using with some sort of DI system you can pass
    // a third parameter callback to get the instance vs new ctrl.
    // bindRoutes(routerRoutes, [ProfileController], (ctrl) => injector.get(ctrl));

    app.use(routerRoutes.routes());
    app.use(routerRoutes.allowedMethods());
}
